﻿﻿using System;
using System.Linq;
using WixSharp;
using WixSharp.CommonTasks;
using WixSharp.Controls;
using Installer;
using IO = System.IO;

const string outputName = "CodRevit";
const string projectName = "CodRevit";

// 创建项目基本配置
var project = new Project
{
    OutDir = "output",
    Name = projectName,
    Platform = Platform.x64,
    UI = WUI.WixUI_FeatureTree,
    MajorUpgrade = MajorUpgrade.Default,
    GUID = new Guid("ECD44425-CB5C-41AA-8020-274CA2B6D6BD"),
    BannerImage = @".\Resources\banner.png",
    BackgroundImage = @".\Resources\background.png",
    Version = new Version("1.0.0"),
    ControlPanelInfo =
    {
        Manufacturer = Environment.UserName,
        ProductIcon = @".\Resources\favicon.ico"
    },
    InstallScope = InstallScope.perMachine
};

project.RemoveDialogsBetween(NativeDialogs.WelcomeDlg, NativeDialogs.CustomizeDlg);

// 获取路径
string currentDir = IO.Directory.GetCurrentDirectory();
string projectRoot = IO.Path.GetFullPath(IO.Path.Combine(currentDir, ".."));
string codRevitBinPath = IO.Path.Combine(projectRoot, "CodRevit", "bin");

try
{
    // 获取所有版本目录，只处理 RVT_xx 格式的目录，忽略 Debug、Release 等
    var versionDirectories = IO.Directory.GetDirectories(codRevitBinPath)
        .Where(dir => 
        {
            var dirName = IO.Path.GetFileName(dir);
            return System.Text.RegularExpressions.Regex.IsMatch(dirName, @"^RVT_\d+$");
        })
        .ToArray();

    if (!versionDirectories.Any())
    {
        throw new InvalidOperationException($"在 {codRevitBinPath} 中未找到任何 RVT_xx 版本目录");
    }

    // 使用新的生成器创建多版本安装配置
    var wixEntities = Generator.GenerateWixEntities(versionDirectories);
    
    // 分离 Feature 和 Dir 实体
    var features = wixEntities.OfType<Feature>().ToArray();
    var dirs = wixEntities.OfType<Dir>().ToArray();
    
    // 应用配置到项目
    project.Features = features;
    project.Dirs = dirs;
    project.OutFileName = $"{outputName}-{project.Version}-MultiVersion";

    // 构建安装包
    Console.WriteLine($"正在构建支持 {features.Length} 个 Revit 版本的安装包...");
    project.BuildMsi();
    Console.WriteLine("安装包构建完成！");
}
catch (Exception ex)
{
    Console.WriteLine($"构建失败: {ex.Message}");
    throw;
}